package m3f.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import m3f.matrix.SparseVector;

public class DenseMatrixReader extends MatrixReader{
	
	private int rows;
	private int columns;
	private String filename;
	private BufferedReader reader;
	private String line;

	@Override
	public void start(String filename) {
		this.filename = filename;
		File file = new File(filename);
		try {
			FileInputStream stream = new FileInputStream(file);
			reader = new BufferedReader(new InputStreamReader(stream));
			// Count the number of lines in the file
			rows = 1;
			long start = System.currentTimeMillis();
			String line = reader.readLine();
			columns = line.split(" ").length;
			while((line = reader.readLine()) != null){
				rows++;
			}
			System.out.println(rows + " vectors with " + columns + 
					" dimensions found in " + file.getName() + " (" 
					+ (System.currentTimeMillis()-start) + "ms)");
			reader.close();
			reader = null;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e){
			e.printStackTrace();
		}
	}

	@Override
	public int getMatrixRows() {
		return rows;
	}

	@Override
	public int getMatrixColumns() {
		return columns;
	}

	@Override
	public ArrayList<SparseVector> readVectors(int numVectors) {
		File file = new File(filename);
		ArrayList<SparseVector> vectors = new ArrayList<SparseVector>();
		try {
			if(reader == null){
				FileInputStream stream = new FileInputStream(file);
				reader = new BufferedReader(new InputStreamReader(stream));
			}
			// Count the number of lines in the file
			long start = System.currentTimeMillis();
			int vectorCounter = 0;
			if(line != null){
				vectors.add(parseRow(line));
				vectorCounter++;
			}
			while((line = reader.readLine()) != null && vectorCounter < numVectors){
				vectors.add(parseRow(line));
				vectorCounter++;
			}
			if(line == null){
				reader.close();
				reader = null;
				//System.out.println(" Closing file");
			}
			//System.out.println(vectorCounter + " vectors read from " + filename + " (" + (System.currentTimeMillis()-start) + "ms)");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e){
			e.printStackTrace();
		}
		return vectors;
	}
	
	private SparseVector parseRow(String row){
		String values[] = row.split(" ");
		if(values.length != columns){
			System.err.println("Error: Reading the file " + filename + "." +
					"Wrong number of columns");
			System.exit(1);
		}
		SparseVector v = new SparseVector();
		for(int i = 0; i < values.length; i++){
			v.setQuick(i, Double.parseDouble(values[i]));
		}
		if(normalizing()) v.normalizeL1();
		return v;
	}
}
